package net.babypai.utils;

import java.io.File;

import net.babypai.common.Constants;


public class DiskCache {
	private static final int DISK_CACHE_SIZE = 100 * 1024 * 1024; // 100MB

	private final File mCacheDir;

	private DiskCache(File cacheDir) {
		mCacheDir = cacheDir;
	}

	public static DiskCache openCache() {
		File cacheDir = getDiskCacheDir(Constants.SDCARDPIC);
		if (!cacheDir.exists()) {
			cacheDir.mkdir();
		}
		if (cacheDir.isDirectory() && cacheDir.canWrite()
				&& NetUtils.getUsableSpace(cacheDir) > DISK_CACHE_SIZE) {
			return new DiskCache(cacheDir);
		} else {
			// clearCache(cacheDir);
		}
		return null;

	}

	public static File getDiskCacheDir(String uniqueName) {
		return new File(uniqueName);
	}

	private static void clearCache(File cacheDir) {
		final File[] files = cacheDir.listFiles();
		for (int i = 0; i < files.length; i++) {
			files[i].delete();
		}
	}

	public static String getFilePath(String url) {
		return TextUtil.formatName(url);
//		try {
//			return URLEncoder.encode(url.replace("*", ""), "UTF-8");
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//			return null;
//		}
	}

	public String createFilePath(File cacheDir, String key) {
		return cacheDir.getAbsolutePath() + File.separator + getFilePath(key);

	}

	/**
	 * Create a constant cache file path using the current cache directory and
	 * an image key.
	 * 
	 * @param key
	 * @return
	 */
	public String createFilePath(String key) {
		return createFilePath(mCacheDir, key);
	}

	public String get(String key) {
		final String existingFile = createFilePath(mCacheDir, key);
		if (new File(existingFile).exists()) {
			return existingFile;
		}

		return null;

	}

	/**
	 * Checks if a specific key exist in the cache.
	 * 
	 * @param key
	 *            The unique identifier for the bitmap
	 * @return true if found, false otherwise
	 */
	public boolean containsKey(String key) {
		final String existingFile = createFilePath(mCacheDir, key);
		if (new File(existingFile).exists()) {
			return true;
		}
		return false;
	}

	/**
	 * Removes all disk cache entries from this instance cache dir
	 */
	public void clearCache() {
		DiskCache.clearCache(mCacheDir);
	}

	public void clearCache(String uniqueName) {
		File cacheDir = getDiskCacheDir(uniqueName);
		clearCache(cacheDir);
	}

}
